<?php

!defined('SYSTEM_INCLUDED') && exit('Access Denied');


SysBase::import('System.Exception.DbException');


//部分改造自Thinkphp的dbMysql.class.php

Class Mysql{

	protected $config = array();

	protected $dbVersion;

	//是否连接成功
	protected $connected = false;

	// 数据库连接ID集合
	protected $linkID              = array();

	// 返回或者影响记录数
	protected $numRows        = 0;


	// 返回最后插入的id值
	protected $lastInsID        = 0;

	// 当前查询ID
	protected $queryID          = null;

	// 结果集
	protected $resultSet          = array();
	
	protected $queryCount = 0;

	public function __Construct($config){
		if ( !extension_loaded('mysql') ) {
			throw new DbException("Mysql Extension is not loaded! Please check your PHP Environment!");
		}
		if(!empty($config)) {
			$this->config = $config;
		}
	}


	//连接，当前仅允许非持久性连接
	public function connect($config='',$linkNum=0){
		if ( !isset($this->linkID[$linkNum]) ) {
			if(empty($config)){
				$config =   $this->config;
			}
			$host = $config['hostname'].($config['hostport']?":{$config['hostport']}":'');
			$this->linkID[$linkNum] = @mysql_connect( $host, $config['username'], $config['password'],true);
			if(!$this->linkID[$linkNum]){
				throw new DbException("Connect Failure!".mysql_error());
			}
			if (!empty($config['database']) && !mysql_select_db($config['database'], $this->linkID[$linkNum]) ) {
				throw new DbException("SELECT DB Failure!".mysql_error());
			}
			//取得mysql数据库版本
			$this->dbVersion = mysql_get_server_info();
			if($this->dbVersion > '4.1') {
				mysql_query("SET NAMES '{$config['dbCharset']}'", $this->linkID[$linkNum]);
			}
			$this->connected = true;
		}
		return $this->linkID[$linkNum];
	}

	//查询sql语句并且返回结果，针对select
	public function query($str,$linkNum=0){
		if ( !isset($this->linkID[$linkNum]) ) {
			throw new DbException("Mysql Doesn't connect yet!");
		}

		//释放前次的查询结果
		if ( $this->queryID ){
			@mysql_free_result($this->queryID);
			$this->queryID = 0;
		}
		$this->queryID = mysql_query($str, $this->linkID[$linkNum]);
		if (!$this->queryID){
			if (DEBUG_MODE){
				throw new DbException("Mysql Query Error! ".mysql_error());
			}else{
				throw new DbException("Mysql Query Error! Please Contact the administrator, or retry it later!");
			}
		}else{
			$this->numRows = mysql_num_rows($this->queryID);
		}
		$this->resultSet = array();
		if($this->numRows > 0) {
			while($row = mysql_fetch_assoc($this->queryID)){
				$this->resultSet[]   =   $row;
			}
			mysql_data_seek($this->queryID,0);
		}
		$this->queryCount++;
		return $this->resultSet;
	}


	//执行sql语句，针对insert等等
	public function execute($str,$linkNum=0){
		if ( !isset($this->linkID[$linkNum]) ) {
			throw new DbException("Mysql Doesn't connect yet!");
		}
		//释放前次的查询结果
		if ( $this->queryID ){
			@mysql_free_result($this->queryID);
			$this->queryID = 0;
		}
		$result =   mysql_query($str, $this->linkID[$linkNum]) ;
		if (false === $result){
			if (DEBUG_MODE){
				throw new DbException("Mysql Execute Error! ".mysql_error());
			}else{
				throw new DbException("Mysql Execute Error! Please Contact the administrator, or retry it later!");
			}
		}else{
			$this->numRows = mysql_affected_rows($this->linkID[$linkNum]);
			$this->lastInsID = mysql_insert_id($this->linkID[$linkNum]);
			$this->queryCount++;
			return $this->numRows;
		}
	}


	//取得查询次数总和
	public function getQueryCount(){
		return $this->queryCount;
	}
	
    //对象被破坏时，进行的close操作
	public function __destruct()
	{
		if((true === $this->connected) && !empty($this->linkID)){
			//释放前次的查询结果
			if ( $this->queryID ){
				@mysql_free_result($this->queryID);
				$this->queryID = 0;
			}
			foreach ($this->linkID as $link){
				@mysql_close($link);
			}
		}
	}

}